var app = getApp()
var util = require('../../utils/util')
var bmap = require('../../utils/bmap-wx.min.js')
let now = util.getStamp(util.formatTime(new Date()));
var cho_shop = require('../../utils/cho_shop')
var suffix;
var interstitialAd = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    img: [],
    activation: false,
    data: '',
    shop: '请授权定位并选择门店',
    name: '',
    phone: '',
    equipment: '',
    area: '请选择所在地区',
    area_real: '',
    salesperson: '',
    avatarUrl: 'https://img10.360buyimg.com/ddimg/jfs/t1/164224/33/3176/1736/6005080bE0d9ade5b/c768fb7219e855f9.png',
    nickName: '用户昵称',
    isOwner: true,
    extend: 0,
    year: 0,
    payfee: 19990,
    z: -1,
    area: '请选择所在地区',
    whetherEmpower: 'yes',
    brand: '',
    model: '',
    getPostion: 1,
    modalName: '',
    // 搜索
    storeName: '',
    nearby: '',
    searchlist: '',
    noticeName: 'notice',
    status: true,
    iconStatus: false,
    searchStatus: false,
    seconds: 6,
  },

  countTime() {
    let that = this;
    let seconds = that.data.seconds - 1;
    //console.log(seconds)
    if (seconds > 0) {
      that.setData({
        seconds
      })
      setTimeout(that.countTime, 1000);
    } else {
      that.setData({
        seconds: 0
      })
    }
  },

  noticeModal(e) {
    this.setData({
      noticeName: 'notice'
    })
  },
  showModal(e) {
    this.setData({
      noticeName: ''
    })
  },

  getMeal(e) {
    let that = this;
    let target = e.currentTarget.dataset.target;
    that.setData({
      modalName: target
    })
    if (target == 'search') {
      cho_shop.load(that, that.data.data.suffix)
    }
  },
  hideModal(e) {
    console.log(e.currentTarget.dataset.target)
    if (e.currentTarget.dataset.target !== null || e.currentTarget.dataset.target !== '') {
      let target = e.currentTarget.dataset.target;
      if (target === 'meal') {
        interstitialAd.show().catch((err) => {
          console.error(err)
        })
      }
    }

    this.setData({
      modalName: null,
      z: -1
    })


  },

  ChooseImage() {
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        console.log(res)
        this.setData({
          img: res.tempFilePaths
        })
        console.log(this.data.img)
      }
    });
  },


  ViewImage(e) {
    wx.previewImage({
      urls: this.data.img,
      current: this.data.img[e.target.dataset.index]
    });
  },

  DelImg(e) {
    let img = this.data.img;
    wx.showModal({
      content: '确定要删除图片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          img.splice(0, 1);
          this.setData({
            img
          })
        }
      }
    })
  },

  toExplainRules() {
    wx.navigateTo({
      url: '/pages/explainRules/explainRules',
    })
  },

  toChoose: function () {
    if (this.data.activation == false) {
      wx.navigateTo({
        url: '../inactivated/chooseBrand/chooseBrand',
      })
    }
  },
  choose: function (e) {
    cho_shop.choose(e, this)
    this.setData({
      modalName: null
    })
  },
  toStoreSearch() {
    wx.navigateTo({
      url: '../storeSearch/storeSearch?suffix=' + this.data.data.suffix,
    })
  },

  // 搜索门店
  //输入框聚焦
  getFocus(e) {
    console.log("聚焦" + e.detail.value);
    this.setData({
      iconStatus: true,
      status: false,
      searchStatus: true
    })
  },

  // 获取input的值
  inputStoreName(e) {
    console.log("input值：" + e.detail.value);
    this.setData({
      storeName: e.detail.value,
    })
    cho_shop.search(this, this.data.data.suffix)
  },
  //失去焦点
  loseFocus(e) {
    console.log("失去焦点：" + e.detail.value);
    if (this.data.storeName != '') {
      this.setData({
        iconStatus: true,
        status: true,
        searchStatus: false
      })
    } else {
      this.setData({
        iconStatus: false,
        status: true,
        searchStatus: false
      })
    }

  },

  empty(e) {
    this.setData({
      storeName: '',
      iconStatus: false
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    let isIphoneX = app.globalData.isIphoneX;
    console.log(isIphoneX)
    this.setData({
      isIphoneX
    })

    that.countTime();

    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-861afafa16ed0280'
      })
      interstitialAd.onLoad(() => {
        console.log(11111)
      })
      interstitialAd.onError((err) => {
        console.log(22222)
      })
      interstitialAd.onClose(() => {
        console.log(3333)
      })
    }

    if (!wx.getStorageSync('userInfo')) {
      let profile;
      if (wx.getUserProfile) {
        profile = 1;
      } else {
        profile = 0;
      }
      setTimeout(() => {
        this.selectComponent("#authorize").showModal("#184CAE", profile);
        //this.retrieval()
      }, 1000)
    }
    if (options) {
      let code;
      console.log(options)
      if (options.data) {
        let data = JSON.parse(options.data)
        code = data.res_code;
        console.log(data)
        setTimeout(() => {
          this.setData({
            data: data,
            payfee: data.extend_one * 100
          })
          that.querystring(data.suffix, code)
        }, 0)
      } else {
        code = options.q.substring(options.q.length - 16)
        let u = '';
        for (let e = 0; e < 5; e++) {
          u += Math.floor(Math.random() * 10)
        }
        if (code == 'LARPR20210400009' || code == 'V010120210400000') {
          code = code.substring(0, 11) + u
        }
        console.log(code)
        var isnum = /^\d+$/.test(code.substring(5));
        var year = parseInt(code.substring(5, 9))
        var month = parseInt(code.substring(9, 11))
        if (!isnum || (year < 2021 || year > 2024) || (month > 12 || month < 1)) {
          wx.showModal({
            title: '产品信息格式错误',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '../index/index',
                })
              }
            }
          })
        }
        util.request('/model/detail', {
          brand_code: code.substring(0, 1),
          category_code: code.substring(1, 3),
          model_code: code.substring(3, 5)
        }, "GET").then(res => {
          console.log(res)
          let list = res.data;
          if (list.length == 0) {
            wx.showModal({
              title: '暂无该产品信息',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '../index/index',
                  })
                }
              }
            })
          }
          list[0].res_code = code;
          that.setData({
            data: list[0],
            payfee: list[0].extend_one * 100
          })
          that.querystring(list[0].suffix, code)
        })
      }

    }
  },
  querystring: function (suffix, code) {
    var that = this;
    util.request('/activation/detail', {
      data: code,
      suffix: suffix
    }, 'GET').then(res => {
      let data = res.data;
      console.log(res)
      if (data.length == 1) {
        wx.cloud.callFunction({
          name: 'login'
        }).then(res => {
          let openid = res.result.openid;
          console.log(openid)
          if (data[0].openid == openid) {
            that.setData({
              isOwner: true
            })
            wx.setNavigationBarTitle({
              title: "我的质保卡"
            })
          } else {
            that.setData({
              isOwner: false
            })
          }
        })
        let year = 0;
        if (data[0].extend_year) {
          year = data[0].extend_year
        }
        let img = [];
        img.push(data[0].warranty_img)
        for (let i in img) {
          img[i] = app.globalData.fileSource + img[i];
        }
        let area = data[0].warranty_area;
        if (area.length > 11) {
          let areaLength = area.length;
          area = '...' + area.substring(areaLength - 7, areaLength)
        }
        that.setData({
          activation: true,
          card: data[0].warranty_card.substring(0, 3) + " " + data[0].warranty_card.substring(3, 6) + " " + data[0].warranty_card.substring(6),
          shop: data[0].warranty_shop,
          brand: data[0].warranty_car,
          img: img,
          name: data[0].warranty_name,
          phone: data[0].warranty_phone,
          area_real: data[0].warranty_area,
          area: area,
          salesperson: data[0].warranty_salesperson,
          sale_openid: data[0].sale_openid,
          nickName: data[0].nickName,
          avatarUrl: data[0].avatarUrl,
          extend: data[0].extend,
          year: year,
          start_date: data[0].start_date,
          end_date: data[0].end_date,
          equipment: data[0].equipment
        })
      } else {
        that.setData({
          isOwner: true,
        })
        //暂只能激活一卡
        /*if (wx.getStorageSync('warranty')) {
          that.setData({
            isOwner: false
          })
        }*/
        var BMap = new bmap.BMapWX({
          ak: 'kbTqZwwOBcpcjzxwNqZG4rn1qsdaHf4P'
        });
        wx.getLocation({
          success(res) {
            console.log(res)
            const lat = res.latitude
            const lon = res.longitude
            BMap.regeocoding({
              location: lat + ',' + lon,
              success: function (res) {
                console.log(res)
                let json = res.originalData.result.addressComponent;
                let area = json.province + '，' + json.city + '，' + json.district
                let areaLength = area.length;
                let areaString = '...' + area.substring(areaLength - 7, areaLength)
                if (areaLength > 11) {
                  that.setData({
                    area: areaString
                  })
                } else {
                  that.setData({
                    area: area
                  })
                }
                that.setData({
                  area_real: area
                })
              },
              fail: function (error) {
                that.setData({
                  getPostion: 0
                })
                console.log(error)
              }
            });
          },
          fail: function (err) {
            that.setData({
              getPostion: 0
            })
          }
        }) /**/
      }
      if (!that.data.activation) {
        that.setData({
          noticeName: ''
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (wx.getStorageSync('chooseBrand')) {
      let brand = wx.getStorageSync('chooseBrand')
      this.setData({
        brand: brand,
        modalName: 'brandConfirm',
        z: 200
      })
      wx.removeStorageSync('chooseBrand')
    }

    if (!wx.getStorageSync('brandList')) {
      var that = this;
      util.request('/car/name', {}, "GET").then(res => {
        let data = res.data;
        wx.setStorageSync('brandList', data)
      })
    }

    if (wx.getStorageSync('shop_label')) {
      let shop = wx.getStorageSync('shop_label')
      this.setData({
        shop: shop
      })
      wx.removeStorageSync('shop_label')
    }
  },
  async activation() {
    var that = this;
    if (wx.getStorageSync('userInfo')) {
      if (that.data.equipment == '') {
        wx.showToast({
          title: '设备号不能为空',
          icon: 'none'
        })
        return
      }
      if (that.data.img == '') {
        wx.showToast({
          title: '请上传照片',
          icon: 'none'
        })
        return
      }
      if (that.data.brand == '') {
        wx.showToast({
          title: '请选择车型',
          icon: 'none'
        })
        return
      }
      if (that.data.name == '') {
        wx.showToast({
          title: '姓名不能为空',
          icon: 'none'
        })
        return
      }
      if (that.data.phone == '') {
        wx.showToast({
          title: '联系电话不能为空',
          icon: 'none'
        })
        return
      } else {
        var reg = /^1[3|4|5|6|7|8|9][0-9]{9}$/; //验证规则
        var flag = reg.test(that.data.phone); //true
        console.log(flag)
        if (flag === false) {
          wx.showToast({
            title: '联系电话错误',
            icon: 'none',
            duration: 1000
          })
          return
        }
      }

      if (that.data.area == '请选择所在地区') {
        wx.showToast({
          title: '请选择地区',
          icon: 'none'
        })
        return
      }
      if (that.data.shop == '请授权定位并选择门店') {
        wx.showToast({
          title: '门店不能为空',
          icon: 'none'
        })
        return
      }
      wx.showLoading({
        title: '激活中',
      })
      util.request('/activation/detail', {
        data: that.data.data.res_code,
        suffix: that.data.data.suffix
      }, "GET").then(res => {
        if (res.data.length == 0) {
          getApp().preventActive(async (res) => {
            if (!app.globalData.PageActive) {
              util.request('/sales/detail', {
                phone: that.data.salesperson,
                suffix: that.data.data.suffix
              }, 'GET').then(res => {
                let openid = 'nothing'
                if (res.data.length > 0) {
                  openid = res.data[0].openid;
                  if (res.data[0].shop !== that.data.shop) {
                    wx.hideLoading()
                    wx.showModal({
                      title: '【销售编码】与【门店名称】不匹配，请联系销售人员重新输入',
                      showCancel: false
                    })
                  } else {
                    wx.uploadFile({
                      url: app.globalData.server + '/upload/image', //仅为示例，非真实的接口地址
                      filePath: that.data.img[0],
                      name: 'file',
                      formData: {
                        'catalog': 'entrucking'
                      },
                      success(res) {
                        console.log(res)
                        that.insert(res.data, openid)
                      },
                      fail: function (res) {
                        console.log(res)
                      }
                    })
                  }
                } else {
                  wx.hideLoading()
                  wx.showModal({
                    title: '【销售编码】不存在，请联系销售人员重新输入',
                    showCancel: false
                  })
                }
              })

            }
          })
        } else {
          wx.showToast({
            title: '该卡已被激活',
            icon: 'none'
          })
        }
      })
    } else {
      let profile;
      if (wx.getUserProfile) {
        profile = 1;
      } else {
        profile = 0;
      }
      this.selectComponent("#authorize").showModal(that.data.data.ml_bg, profile);
    }
  },
  insert: function (image, openid) {
    var that = this;
    wx.showLoading({
      title: '激活中',
    })
    let code = ''
    for (let e = 0; e < 10; e++) {
      code += Math.floor(Math.random() * 10)
    }
    let start = util.toDate(now, 'Y/M/D', 86400)
    let end = util.toDate(now, 'Y/M/D', 31536000 + 86400)
    let userInfo = wx.getStorageSync('userInfo')
    let info = {
      suffix: that.data.data.suffix,
      equipment: that.data.equipment,
      creation_date: util.formatTime(new Date()),
      creation_timestamp: Date.parse(util.formatTime(new Date()).replace(/-/g, '/')) / 1000,
      openid: app.globalData.openid,
      nickName: userInfo.nickName,
      avatarUrl: userInfo.avatarUrl,
      warranty_name: that.data.name,
      warranty_card: code,
      warranty_code: that.data.data.res_code,
      warranty_brand: that.data.data.brand_name,
      warranty_brand_code: that.data.data.res_code.substring(0, 1),
      warranty_category: that.data.data.category_name,
      warranty_category_code: that.data.data.res_code.substring(1, 3),
      warranty_model: that.data.data.model_name,
      warranty_model_code: that.data.data.res_code.substring(3, 5),
      warranty_shop: that.data.shop,
      warranty_car: that.data.brand + ' ' + that.data.model,
      warranty_phone: that.data.phone,
      warranty_area: that.data.area_real,
      warranty_salesperson: that.data.salesperson,
      sale_openid: openid,
      warranty_img: image,
      start_date: start,
      end_date: end,
      extend: 0
    };
    util.request('/activation/insert', info, "POST").then(res => {
      console.log(res)
      wx.hideLoading({
        success: (res) => {},
      })
      wx.setStorageSync('warranty', info)
      that.setData({
        activation: true,
        start_date: start,
        end_date: end,
        card: code.substring(0, 3) + " " + code.substring(3, 6) + " " + code.substring(6),
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl,
        sale_openid: openid
      })
      wx.showToast({
        title: '激活成功',
        icon: 'success',
        duration: 2000
      })
      if (wx.pageScrollTo) {
        wx.pageScrollTo({
          scrollTop: 0
        })
      }
      setTimeout(() => {
        that.setData({
          modalName: 'meal'
        })
      }, 1000)
    })

  },
  modify: function () {
    var that = this;
    if (wx.getStorageSync('userInfo')) {
      getApp().preventActive(async (res) => {
        if (!app.globalData.PageActive) {
          if (that.data.activation && that.data.isOwner) {
            let userInfo = wx.getStorageSync('userInfo')
            util.request('/activation/update/info', {
              warranty_area: that.data.area_real,
              warranty_name: that.data.name,
              warranty_phone: that.data.phone,
              avatarUrl: userInfo.avatarUrl,
              nickName: userInfo.nickName,
              warranty_code: that.data.data.res_code,
              suffix: that.data.data.suffix
            }, "POST").then(res => {
              console.log(res)
              let warranty = wx.getStorageSync('warranty')
              warranty.warranty_salesperson = that.data.salesperson
              warranty.warranty_area = that.data.area_real
              warranty.warranty_name = that.data.name
              warranty.warranty_phone = that.data.phone
              wx.setStorageSync('warranty', warranty)
            })
          }
        }
      })
    } else {
      let profile;
      if (wx.getUserProfile) {
        profile = 1;
      } else {
        profile = 0;
      }
      this.selectComponent("#authorize").showModal(that.data.data.ml_bg, profile);
    }
  },
  inputShop: function (e) {
    this.setData({
      shop: e.detail.value
    })
  },
  inputName: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  inputPhone: function (e) {
    this.setData({
      phone: e.detail.value
    })
  },
  inputEquipment: function (e) {
    console.log(e)
    this.setData({
      equipment: e.detail.value
    })
  },
  inputPerson: function (e) {
    this.setData({
      salesperson: e.detail.value
    })
  },
  inputBrand: function (e) {
    this.setData({
      brand: e.detail.value
    })
  },
  inputModel: function (e) {
    this.setData({
      model: e.detail.value
    })
  },
  bindRegionChange: function (e) {
    var region = e.detail.value;
    let area = region.join('，');
    this.setData({
      area_real: area
    })
    //this.modify();
    console.log()
    let areaLength = area.length;
    let areaString = '...' + area.substring(areaLength - 7, areaLength)
    console.log(areaString)
    if (areaLength > 11) {
      this.setData({
        area: areaString
      })
    } else {
      this.setData({
        area
      })
    }
  },
  getPhoneNumber: function (e) {
    var that = this;
    //console.log(e)
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.showLoading({
        title: '授权中',
      })
      wx.cloud.callFunction({
        name: 'decode',
        data: {
          weRunData: wx.cloud.CloudID(e.detail.cloudID),
        }
      }).then(res => {
        that.setData({
          phone: res.result,
        })
        that.modify()
        wx.hideLoading()
        that.setData({
          modalName: null
        })
        wx.showToast({
          title: '授权成功',
          icon: 'success'
        })
      }, err => {
        console.log(err)
        wx.hideLoading()
        wx.showToast({
          title: '授权失败',
          icon: 'none'
        })
      })
    }
  },
  phoneModal: function () {
    this.setData({
      modalName: 'phoneModal',
      z: 200
    })
  },
  changeInput: function () {
    var _this = this;
    setTimeout(res => {
      _this.setData({
        whetherEmpower: 'no',
        modalName: null
      })
    })
  },
  changeEmpower: function () {
    this.setData({
      whetherEmpower: 'yes'
    })
    this.modify()
  },
  phoneConfirm: function (e) {
    this.setData({
      phone: e.detail.value
    })
  },
  payfee: function () {
    var that = this;
    if (that.data.activation) {
      var stamp = util.getStamp(util.formatTime(new Date()));
      var str = util.getRandomCode(12)
      let No = "LB" + stamp + util.getRandomCode()
      wx.showLoading({
        title: '支付中',
      })
      wx.cloud.callFunction({
        name: 'payment',
        data: {
          str: str,
          body: "蜂鸟创客（深圳）技术有限公司-延保支付",
          No: No,
          totalFee: that.data.payfee
        },
        success(res) {
          console.log(res)
          that.pay(res.result.payment, No, that.data.payfee / 100)
          wx.hideLoading()
        },
        fail(error) {
          wx.hideLoading()
          console.log(error)
        },
      })
    } else {
      wx.showToast({
        title: '该卡还未激活',
        icon: 'none'
      })
    }
  },
  pay(payData, number, payfee) {
    var py = this;
    wx.requestPayment({
      nonceStr: payData.nonceStr,
      package: payData.package,
      paySign: payData.paySign,
      timeStamp: payData.timeStamp,
      signType: 'MD5',
      success(res) {
        console.log(res)
        let year = 1
        if (py.data.payInd == 1) {
          year = 2
        }
        let sale_openid = py.data.sale_openid;
        const info = {
          creation_date: util.formatTime(new Date()),
          creation_timestamp: Date.parse(util.formatTime(new Date()).replace(/-/g, '/')) / 1000,
          order_no: number,
          salesperson: py.data.salesperson,
          openid: wx.getStorageSync('openid'),
          payfee: payfee,
          shop: py.data.shop,
          warranty_code: py.data.data.res_code,
          sale_openid: sale_openid,
          brand_code: py.data.data.res_code.substring(0, 1),
          category_code: py.data.data.res_code.substring(1, 3),
          model_code: py.data.data.res_code.substring(3, 5),
        };
        util.request('/order/insert', info, "POST").then(res => {
          console.log(res)
          if (sale_openid !== 'nothing') {
            console.log(Math.ceil((payfee * 100) * res.data), Math.ceil((payfee * 100) * res.data) / 100)
            util.request('/sales/update/income', {
              openid: sale_openid,
              type: 'income',
              income: Math.ceil((payfee * 100) * res.data) / 100,
              suffix: py.data.data.suffix
            }, 'POST').then(res => {

            })
            util.request('/smallchange', {
              openid: sale_openid,
              money: Math.ceil((payfee * 100) * res.data),
              order_no: number,
              brand_code: py.data.data.res_code.substring(0, 1),
              suffix: py.data.data.suffix
            }, 'POST').then(res => {
              console.log(res)
            })
          }
        })
        let endstamp = Date.parse(py.data.end_date.replace(/-/g, '/')) / 1000;
        console.log(endstamp, py.data.end_date)
        let end = util.toDate(endstamp, 'Y/M/D', 31536000 * year)
        console.log(end)
        py.setData({
          modalName: null,
          extend: 1,
          year: year,
          end_date: end,
        })
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        })
        setTimeout(() => {
          wx.showModal({
            title: '您已经成功延保' + year + '年',
            showCancel: false,
          })
        }, 1000)
        util.request('/activation/update', {
          extend: 1,
          extend_year: year,
          extend_fee: payfee,
          end_date: end,
          warranty_code: py.data.data.res_code,
          suffix: py.data.data.suffix
        }, "POST").then(res => {

        })
        setTimeout(() => {
          interstitialAd.show().catch((err) => {
            console.error(err)
          })
        }, 1500)


      },
      fail(res) {
        console.log(res)
        wx.showToast({
          title: '支付未成功',
          duration: 1000,
          image: "none",
        })

        setTimeout(() => {
          interstitialAd.show().catch((err) => {
            console.error(err)
          })
        }, 1500)
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "品牌联保服务",
      imageUrl: 'http://file.funiaopark.com/images/action/philips/public/public-1Vtgsi-676107.jpg',
      path: '/pages/index/index'
    }
  }
})